package com.hos.punchtheclocksystem.service.impl;

import com.hos.punchtheclocksystem.mapper.AccountMapper;
import com.hos.punchtheclocksystem.pojo.DoctorAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;


@Service
public class SysUserService {
    //自动注入redis
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private AccountMapper mapper;

    //根据用户id获取用户信息
    public DoctorAccount selectSysUserByUserId(Integer userId){
        //修改key的序列化类型 提高可读行 StringRedisSerializer设置key的类型为string
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //从redis缓存中查询
        DoctorAccount sysUser = (DoctorAccount) redisTemplate.opsForValue().get("sysUser");
        //如果为空则从数据库查询
        if(sysUser == null){
            synchronized (this) {
                //从数据库查询
                sysUser = mapper.selectDoctorByDocId(userId);
                //存入redis中
                redisTemplate.opsForValue().set("sysUser", sysUser);
            }
        }
        return sysUser;
    }
}

